//index.js
var h5MapPort;

// 地图事件，通信，打点，连线
window.addEventListener('message', function(event) {
    if (event.data == 'h5MapPort') {
        if(event.ports[0] != null) {
            h5MapPort = event.ports[0]; // 1. 保存从ets侧发送过来的端口
            h5MapPort.onmessage = function(event) {
                var result = event.data;
                if (typeof(result) == "string") {
                    if(result.startsWith("init")){
                        // 初始化地图中心点
                        initMap(result.split("@")[1], "0.16");
                        console.log(`===js端收到数据${result}`)
                    }
                    else if(result == "clear"){
                        map.clearMap();
                    }else {
                        // 打点 x1@x2 其中x1,x2为经纬度
                        console.log("In html got message, String: ", result);
                        t = result.split('@')
                        if (isNaN(Number(t[2]))) {
                            t[2] = -1;
                        }
                        else if(isNaN(Number(t[3]))){
                            t[3] = 0;
                        }
                        creatTag(t[0], t[1], t[2], t[3]);        // 打点
                    }
                }
                else if (typeof(result) == "object") {
                    if (result instanceof Array) {
                        putLine(result)
                    } else {
                        console.log("not my type");
                    }
                }
                else {
                    console.log("not support type");
                }
            }
            h5MapPort.onmessageerror = (event) => {
                console.error(`hwd In html Error receiving message: ${event}`);
            };
        }
    }
})


// 使用h5MapPort往ets侧发送String类型的消息.
function postStringToApp() {
    if (h5MapPort) {
        h5MapPort.postMessage("hello");
    } else {
        console.error("In html h5MapPort is null, please init first");
    }
}
